package com.example.demo.幂等性控制.aop;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Collections;

/**
 * @description:
 * @projectName:demo
 * @see:com.example.demo.幂等性控制.aop
 * @author:袁成龙
 * @createTime:2020/10/14 10:23
 * @version:1.0
 */
@Aspect
@Component
public class MdxAop {

    @Autowired
    private RedisTemplate<String,String> redisTemplate;


    //定义切入点
    @Pointcut("execution(public * com.example.demo.幂等性控制.controller.TestMdxController.*(..))")
    public void qierudian(){}


    @Around("qierudian() && @annotation(com.example.demo.幂等性控制.anniontion.CheckKey)")
    public Object around(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes)RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = requestAttributes.getRequest();
        String key = request.getParameter("key");
        //System.out.println("======key===="+key);

        //校验这个Key
        if(checkkey( key)){
            return proceedingJoinPoint.proceed();
        }else{
            return null;
        }

    }



    public boolean checkkey(String key){
        String checkScript="if redis.call('get',KEYS[1]) then return redis.call('del',KEYS[1]) else return 0 end";
       // System.out.println("--------"+checkScript);
        DefaultRedisScript<Long> defaultRedisScript=new DefaultRedisScript<>();
        defaultRedisScript.setScriptText(checkScript);
        defaultRedisScript.setResultType(Long.class);
        Long execute = redisTemplate.execute(defaultRedisScript, Collections.singletonList(key));

       /* DefaultRedisScript<Long> objectDefaultRedisScript = new DefaultRedisScript<>();
        objectDefaultRedisScript.setScriptText(checkScript);
        objectDefaultRedisScript.setResultType(Long.class);
        Long execute = redisTemplate.execute(objectDefaultRedisScript, Collections.singletonList(key));*/
       // System.out.println("PPPPPPPPPPPPPPP==="+execute);
        if(execute==1){
            return true;
        }else{
            return false;
        }
    }

}